package com.jht.bletool2kotlin.activity.homepage.fragment.device

import android.Manifest
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.hjq.permissions.OnPermission
import com.hjq.permissions.XXPermissions
import com.jht.bletool2kotlin.BLEApplication
import com.jht.bletool2kotlin.R
import com.jht.bletool2kotlin.activity.blepage.BlePageActivity
import com.jht.bletool2kotlin.activity.homepage.HomeActivity
import com.jht.bletool2kotlin.activity.homepage.fragment.device.adapter.BleDeviceAdapter
import com.jht.bletool2kotlin.activity.homepage.fragment.device.bean.BLEDevice
import com.jht.bletool2kotlin.activity.homepage.fragment.device.itemanim.SlideInBottomAnimAdapter
import com.jht.bletool2kotlin.config.BLEConfig
import it.gmariotti.recyclerview.adapter.SlideInBottomAnimatorAdapter
import kotlinx.android.synthetic.main.fragment_device.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

private const val TAG = "DeviceFragment"
class DeviceFragment : Fragment(), IDevice.UI {
    private lateinit var presenter: DevicePresenter
    private lateinit var bluetoothManager: BluetoothManager
    private lateinit var bleDeviceAdapter: BleDeviceAdapter
    private val deviceHandler = object : Handler(Looper.getMainLooper()){}
    private val btScanRunnable = Runnable {
        startBTScan()
    }

    private val stopBTScanRunnable = Runnable {
        stopBTScan()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bluetoothManager = BLEApplication.appContext
            .getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        presenter = DevicePresenter(this)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_device, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initRecyclerView()
        initSmartRefreshLayout()
    }

    private fun initSmartRefreshLayout() {
        refresh_layout.setOnRefreshListener {
            if (isBTOpen() && isGPSOpen()) {
                requestPermission()
            } else {
                "打开蓝牙和定位！".showToast()
            }
            refresh_layout.finishRefresh(1000)
        }
    }

    private fun requestPermission() {
        XXPermissions.with(activity)
            .permission(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION
            )
            .request(object : OnPermission {
                /**
                 * 1.蓝牙和定位是否开启：是-扫描设备，否-提醒用户打开蓝牙和定位
                 *
                 */
                override fun hasPermission(granted: List<String>, all: Boolean) {
                    if (all) {
                        //清除之前扫描的数据
                        bleDeviceAdapter.clear()
                        //权限全部授予,开始搜素蓝牙
                        deviceHandler.postDelayed(btScanRunnable,1000)
                        //定时关闭蓝牙
                        deviceHandler.postDelayed(stopBTScanRunnable,BLEConfig.scanTime*1000.toLong())
                    }
                }

                override fun noPermission(denied: List<String>, existNever: Boolean) {
                    if (existNever) {
                        //存在永久拒绝的权限，解释原因，并跳转到权限授予界面
                    } else {
                        //解释为什么必须授予全部权限
                    }
                }
            })
    }

    private fun isGPSOpen(): Boolean {
        val locationManager =
            BLEApplication.appContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val gpsLocation = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        val networkLocation = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        return gpsLocation || networkLocation
    }

    private fun isBTOpen(): Boolean {
        return bluetoothManager.adapter.isEnabled
    }

    private fun initRecyclerView() {
        val linearLayoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        lv_ble_devices.layoutManager = linearLayoutManager
        bleDeviceAdapter = BleDeviceAdapter(activity as Context)
        //注意这里对BleDeviceAdapter封装了一层，变成了新的带item动画Adapter，新的adapter方法可能实现的不完整
        val animatorAdapter: SlideInBottomAnimAdapter<BleDeviceAdapter.BleDeviceViewHolder> =
            SlideInBottomAnimAdapter(bleDeviceAdapter, lv_ble_devices)
        lv_ble_devices.adapter = animatorAdapter
    }

    private fun String.showToast() {
        Toast.makeText(BLEApplication.appContext, this, Toast.LENGTH_SHORT).show()
    }

    override fun onStart() {
        super.onStart()
        Log.e(TAG, "onStart: ")
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        Log.e(TAG, "onStop: ")
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun goBlePage(device: DeviceAdapterEvent) {
        if (activity == null) {
            return
        }
        deviceHandler.removeCallbacks(stopBTScanRunnable)
        stopBTScan()
        val intent = Intent(activity, BlePageActivity::class.java)
        intent.putExtra("ble_device", device.bleDevice)
        startActivity(intent)
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun stopScanEvent(homeUIEvent: HomeActivityEvent) {
        deviceHandler.removeCallbacks(btScanRunnable)
        deviceHandler.removeCallbacks(stopBTScanRunnable)
        stopBTScan()
        Log.d(TAG, "stopScanEvent: ")
        EventBus.getDefault().post(HomeActivity.UIEvent(HomeActivity.Type.GO_SETTING_ACTIVITY))
    }

    override fun stopBTScan() {
        presenter.stopScanBle(bluetoothManager.adapter)
        EventBus.getDefault().post(HomeActivity.UIEvent(HomeActivity.Type.CLOSE_PROCESS_BAR))
    }

    override fun startBTScan(){
        presenter.startScanBle(bluetoothManager.adapter)
        EventBus.getDefault().post(HomeActivity.UIEvent(HomeActivity.Type.OPEN_PROCESS_BAR))
    }

    companion object {
        @JvmStatic
        fun newInstance() = DeviceFragment()
    }

    override fun addBleDevice(bt: BLEDevice?) {
        if (bt == null) return
        bleDeviceAdapter.addDevice(bt)
    }

    class DeviceAdapterEvent(val bleDevice: BLEDevice)

    class HomeActivityEvent
}